<script setup>
import { ref, onMounted } from 'vue'
import { ElTable, ElTableColumn, ElButton, ElIcon, ElInput, ElSelect, ElOption, ElForm, ElFormItem, ElCard, ElNotification } from 'element-plus'
import { Search, Refresh, Download, Filter } from '@element-plus/icons-vue'

// 学生成绩数据
const performanceData = ref([])
// 搜索关键词
const searchKeyword = ref('')
// 当前页码
const currentPage = ref(1)
// 每页条数
const pageSize = ref(10)
// 总条数
const total = ref(0)
// 加载状态
const loading = ref(false)
// 排序字段
const sortField = ref('totalScore')
// 排序方向
const sortDirection = ref('descending')
// 班级筛选
const classFilter = ref('all')
// 查询表单引用
const queryForm = ref(null)

// 班级选项
const classOptions = ref([
  { value: 'all', label: '全部班级' },
  { value: '1班', label: '1班' },
  { value: '2班', label: '2班' },
  { value: '3班', label: '3班' },
  { value: '4班', label: '4班' },
  { value: '5班', label: '5班' }
])

// 加载学生成绩数据
const loadPerformanceData = async () => {
  loading.value = true
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    // 模拟数据
    const mockData = Array.from({ length: 50 }, (_, index) => {
      const chinese = Math.floor(Math.random() * 40) + 60
      const math = Math.floor(Math.random() * 40) + 60
      const english = Math.floor(Math.random() * 40) + 60
      const physics = Math.floor(Math.random() * 40) + 60
      const chemistry = Math.floor(Math.random() * 40) + 60
      const biology = Math.floor(Math.random() * 40) + 60
      const totalScore = chinese + math + english + physics + chemistry + biology
      const className = `${Math.floor(Math.random() * 5) + 1}班`

      return {
        id: index + 1,
        name: `学生${index + 1}`,
        studentId: `2023000${index + 1}`,
        class: className,
        chinese,
        math,
        english,
        physics,
        chemistry,
        biology,
        totalScore,
        ranking: 0 // 后续计算
      }
    })

    // 计算排名
    const sortedData = [...mockData].sort((a, b) => b.totalScore - a.totalScore)
    sortedData.forEach((item, index) => {
      item.ranking = index + 1
    })

    // 筛选数据
    let filteredData = sortedData
    if (searchKeyword.value) {
      filteredData = sortedData.filter(item =>
        item.name.includes(searchKeyword.value) ||
        item.studentId.includes(searchKeyword.value)
      )
    }
    if (classFilter.value !== 'all') {
      filteredData = filteredData.filter(item => item.class === classFilter.value)
    }

    // 排序
    if (sortField.value) {
      filteredData.sort((a, b) => {
        if (sortDirection.value === 'ascending') {
          return a[sortField.value] - b[sortField.value]
        } else {
          return b[sortField.value] - a[sortField.value]
        }
      })
    }

    // 分页
    total.value = filteredData.length
    performanceData.value = filteredData.slice(
      (currentPage.value - 1) * pageSize.value,
      currentPage.value * pageSize.value
    )
  } catch (error) {
    ElNotification.error('获取学生成绩失败')
    console.error('Failed to load performance data:', error)
  } finally {
    loading.value = false
  }
}

// 搜索学生
const searchStudents = () => {
  currentPage.value = 1
  loadPerformanceData()
}

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = ''
  classFilter.value = 'all'
  currentPage.value = 1
  if (queryForm.value) {
    queryForm.value.resetFields()
  }
  loadPerformanceData()
}

// 下载数据
const downloadData = () => {
  ElNotification.info('数据下载中...')
  // 实际应用中这里应该实现数据导出功能
}

// 刷新数据
const refreshData = () => {
  loadPerformanceData()
}

// 显示筛选
const showFilter = () => {
  ElNotification.info('筛选功能')
  // 实际应用中这里应该实现筛选功能
}

// 页面加载时初始化
onMounted(() => {
  loadPerformanceData()
})
</script>

<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="clearfix">
          <span>学生成绩管理</span>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="68px"
        class="query-form"
      >
        <el-form-item label="班级" prop="class">
          <el-select
            v-model="classFilter"
            placeholder="请选择班级"
            clearable
            style="width: 150px"
            @change="searchStudents"
          >
            <el-option v-for="option in classOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="关键字" prop="keyword">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入学生姓名或学号"
            clearable
            style="width: 250px"
            @keyup.enter="searchStudents"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="searchStudents">搜索</el-button>
          <el-button icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="action-buttons">
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
        <el-button @click="downloadData">
          <el-icon><Download /></el-icon>导出
        </el-button>
        <el-button @click="showFilter">
          <el-icon><Filter /></el-icon>筛选
        </el-button>
      </div>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="performanceData"
        border
        style="width: 100%"
      >
        <el-table-column prop="ranking" label="排名" width="80" align="center" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="studentId" label="学号" />
        <el-table-column prop="class" label="班级" width="100" align="center" />
        <el-table-column prop="chinese" label="语文" width="80" align="center" />
        <el-table-column prop="math" label="数学" width="80" align="center" />
        <el-table-column prop="english" label="英语" width="80" align="center" />
        <el-table-column prop="physics" label="物理" width="80" align="center" />
        <el-table-column prop="chemistry" label="化学" width="80" align="center" />
        <el-table-column prop="biology" label="生物" width="80" align="center" />
        <el-table-column
          prop="totalScore"
          label="总分"
          width="80"
          align="center"
          :class-name="'total-score'"
        />
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.app-container {
  padding: 20px;
}

.query-form {
  margin-bottom: 20px;
}

.action-buttons {
  margin-bottom: 20px;
}

.total-score {
  font-weight: bold;
  color: #4096ff;
}
</style>